import storage from '@/utils/storage'
import constant from '@/utils/constant'
import loginApi from '@/api/login'
import {
	setToken,
	removeToken
} from '@/utils/auth'
import defaultAvatar from '@/static/images/profile.png'
const user = {
	state: {
		tenantList: storage.get(constant.tenantList), // 租户列表
		currentTenantId: storage.get(constant.currentTenantId) || 188, // 当前租户id
		deptList: storage.get(constant.deptList), // 公司列表
		currentDeptId: storage.get(constant.currentDeptId), // 公司id
		currentDeptName: storage.get(constant.currentDeptName), // 公司名称
		companyType: storage.get(constant.companyType), // 公司类型
		companyId: storage.get(constant.companyId), // 公司id
		userId: storage.get(constant.userId), // 用户编号
		name: storage.get(constant.name),
		avatar: storage.get(constant.avatar),
		roles: storage.get(constant.roles),
		permissions: storage.get(constant.permissions),
		userInfo: storage.get(constant.userInfo),
		userType: storage.get(constant.userType), // 1：供应链 2: 供应商
	},

	mutations: {
		SET_TENANT_LIST: (state, tenantList) => {
			state.tenantList = tenantList
			storage.set(constant.tenantList, tenantList)
		},
		SET_CURRENT_TENANT: (state, currentTenantId) => {
			state.currentTenantId = currentTenantId
			storage.set(constant.currentTenantId, currentTenantId)
		},
		SET_DEPT_LIST: (state, deptList) => {
			state.deptList = deptList
			storage.set(constant.deptList, deptList)
		},
		SET_CURRENT_DEPT_ID: (state, currentDeptId) => {
			state.currentDeptId = currentDeptId
			storage.set(constant.currentDeptId, currentDeptId)
		},
		SET_CURRENT_DEPT_NAME: (state, currentDeptName) => {
			state.currentDeptName = currentDeptName
			storage.set(constant.currentDeptName, currentDeptName)
		},
		SET_COMPANY_TYPE: (state, companyType) => {
			state.companyType = companyType
			storage.set(constant.companyType, companyType)
		},
		SET_COMPANY_ID: (state, companyId) => {
			state.companyId = companyId
			storage.set(constant.companyId, companyId)
		},
		SET_USER_ID: (state, userId) => {
			state.userId = userId
			storage.set(constant.userId, userId)
		},
		SET_NAME: (state, name) => {
			state.name = name
			storage.set(constant.name, name)
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
			storage.set(constant.avatar, avatar)
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles
			storage.set(constant.roles, roles)
		},
		SET_PERMISSIONS: (state, permissions) => {
			state.permissions = permissions
			storage.set(constant.permissions, permissions)
		},
		SET_USERINFO: (state, userInfo) => {
			state.userInfo = userInfo
			storage.set(constant.userInfo, userInfo)
		},
		SET_USER_TYPE: (state, userType) => {
			state.userType = userType
			storage.set(constant.userType, userType)
		}
	},

	actions: {
		// 获取供应链注册状态
		GetRegisterInfo() {
			return new Promise((resolve, reject) => {
				loginApi.getRegisterInfo().then(res => {
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 发送验证码
		SendMsgCode({ commit, state }, mobile) {
			return new Promise((resolve, reject) => {
				loginApi.sendMsgCode({
					mobile,
					scene: 21
				}).then(res => {
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 手机号登录
		LoginByPhone({ commit, state }, userInfo) {
			commit('SET_CURRENT_TENANT', 1)
			const mobile = userInfo.phone
			const code = userInfo.code
			return new Promise((resolve, reject) => {
				loginApi.loginByPhone({
					mobile,
					code,
					loginType: 10
				}).then(res => {
					res = res.data
					const tenants = res.tenants || []
					tenants.forEach(item => {
						item.title = item.name.replace('-SCM', '')
					})
					commit('SET_USER_ID', res.userId)
					commit('SET_CURRENT_TENANT', res.tenantId)
					commit('SET_TENANT_LIST', tenants)
					// 设置 token
					setToken(res)
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 密码登录
		LoginByPassword({ commit, state }, userInfo) {
			commit('SET_CURRENT_TENANT', 1)
			return new Promise((resolve, reject) => {
				loginApi.loginByPassword({
					...userInfo,
					loginType: 10
				}).then(res => {
					res = res.data
					const tenantList = res.tenants || []
					tenantList.forEach(item => {
						item.title = item.name.replace('-SCM', '')
					})
					commit('SET_USER_ID', res.userId)
					commit('SET_CURRENT_TENANT', res.tenantId)
					commit('SET_TENANT_LIST', tenantList)
					// 设置 token
					setToken(res)
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 获取租户列表
		GetTenantList({ commit, state }) {
			return new Promise((resolve, reject) => {
				loginApi.getTenantList(state.userId).then(res => {
					const tenantList = res.data || []
					tenantList.forEach(item => {
						item.title = item.name.replace('-SCM', '')
					})
					commit('SET_TENANT_LIST', tenantList)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 获取部门列表
		GetDeptList({ commit, state }) {
			return new Promise((resolve, reject) => {
				loginApi.getDeptList(state.userId).then(res => {
					const deptList = res.data || []
					commit('SET_DEPT_LIST', deptList)
					commit('SET_CURRENT_DEPT_ID', deptList[0] ? deptList[0].deptId : state.currentDeptId)
					commit('SET_CURRENT_DEPT_NAME', deptList[0] ? deptList[0].name : state.currentDeptName)
					commit('SET_COMPANY_TYPE', deptList[0] ? deptList[0].type : state.companyType)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 获取用户信息
		GetUserInfo({ commit, state }) {
			return new Promise((resolve, reject) => {
				loginApi.getUserInfo({
					id: state.userId,
					deptid: state.currentDeptId,
					type: state.companyType,
				}).then(res => {
					const user = res.data || {}
					const userArr = user.userType ? user.userType.split(',') : []
          const userType = userArr.indexOf('2') > -1 ? '2' : '1'
					commit('SET_CURRENT_DEPT_ID', user.deptId)
					commit('SET_COMPANY_ID', user.supplierId)
					commit('SET_USERINFO', user)
					commit('SET_USER_TYPE', userType)
					commit('SET_ROLES', (user.roles || []).map(item => item.code))
					const avatar = (user == null || user.avatar === "" || user.avatar == null) ?
						defaultAvatar : user.avatar
					const nickname = (user == null || user.nickname === "" || user.nickname ==
						null) ? "" : user.nickname
					commit('SET_NAME', nickname)
					commit('SET_AVATAR', avatar)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 退出系统
		LogOut({ commit, state }) {
			return new Promise((resolve, reject) => {
				commit('SET_TENANT_LIST', [])
				commit('SET_CURRENT_TENANT', 1)
				commit('SET_DEPT_LIST', [])
				commit('SET_CURRENT_DEPT_ID', '')
				commit('SET_CURRENT_DEPT_NAME', '')
				commit('SET_COMPANY_TYPE', '')
				commit('SET_COMPANY_ID', '')
				commit('SET_USER_ID', '')
				commit('SET_USERINFO', {})
				commit('SET_USER_TYPE', '')
				commit('SET_NAME', '')
				commit('SET_AVATAR', '')
				commit('SET_ROLES', [])
				commit('SET_PERMISSIONS', [])
				removeToken()
				storage.clean()
				uni.reLaunch({
					url: '/pages/login'
				})
				resolve()
			})
		},

		// 注销账号
		LogOff({ commit, state }) {
			return new Promise((resolve, reject) => {
				loginApi.logOffUser(state.userId).then(res => {
					commit('SET_TENANT_LIST', [])
					commit('SET_CURRENT_TENANT', 1)
					commit('SET_DEPT_LIST', [])
					commit('SET_CURRENT_DEPT_ID', '')
					commit('SET_CURRENT_DEPT_NAME', '')
					commit('SET_COMPANY_TYPE', '')
					commit('SET_COMPANY_ID', '')
					commit('SET_USER_ID', '')
					commit('SET_USERINFO', {})
					commit('SET_USER_TYPE', '')
					commit('SET_NAME', '')
					commit('SET_AVATAR', '')
					commit('SET_ROLES', [])
					commit('SET_PERMISSIONS', [])
					removeToken()
					storage.clean()
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 退出系统：切换租户时使用
		LogoutTenant({ commit, state }) {
			return new Promise((resolve, reject) => {
				loginApi.logout(state.token).then(() => {
					removeToken()
					resolve()
				})
			})
		},

		// 切换租户id
		SetTenantId({ commit, state }, tenantId) {
			return new Promise((resolve) => {
				commit('SET_CURRENT_TENANT', tenantId || 1)
				resolve()
			})
		},

		// 切换租户的登录
		LoginTenant({ commit, state }, userInfo) {
			return new Promise((resolve, reject) => {
				loginApi.loginTenant(userInfo).then(res => {
					res = res.data
					commit('SET_USER_ID', res.userId)
					// 设置 token
					setToken(res)
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},
	}
}

export default user